package fyp.mobile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import view.Core.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SearchTypeActivity extends Activity {

	public static final int REQUEST_CODE = 3421;
	ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listview01);

		ListView list = (ListView) findViewById(R.id.MyListView);

		selectHistoryFromDB();

		SimpleAdapter mSchedule = new SimpleAdapter(this, mylist,
				R.layout.my_listitem3, new String[] { "ItemTitle", "ItemText" },
				new int[] { R.id.ItemTitle, R.id.ItemText });

		list.setAdapter(mSchedule);

		list.setOnItemClickListener(new OnItemClickListener() {

			HashMap<String, String> item = new HashMap<String, String>();

			@Override
			public void onItemClick(android.widget.AdapterView<?> arg0,
					View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				onItemSelected(null, arg1, arg2, arg3);

			}
		});

	}

	public void selectHistoryFromDB() {

		// ///http get
		String url = getResources().getString(R.string.serverURL)
				+ "getType.php";
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			String line = "";
			String reply = "";
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			while ((line = reader.readLine()) != null) {
				reply += line;
			}
			reader.close();
			// ///JSONArray
			try {
				JSONArray json = new JSONArray(reply);
				JSONArray jsonB = new JSONArray(json.getString(0));

				int count = jsonB.length();
				for (int i = 0; i < count; i++) {
					// String getField = jsonB.getString(i);
					JSONObject getField = new JSONObject(jsonB.getString(i));
					HashMap<String, String> item = new HashMap<String, String>();

					item.put("ItemTitle", getField.getString("typeName"));
					item.put("ItemText", getField.getString("typeID"));
					mylist.add(item);
				}

			} catch (JSONException e) {
				errorToast("" + e);
			}

		} catch (Exception e) {
			errorToast("" + e);
		}

	}

	public void errorToast(String msg) {
		Toast.makeText(this, "" + msg, Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		super.onCreateOptionsMenu(menu);

		menu.add(Menu.NONE, Menu.FIRST + 1, Menu.NONE, "Back").setShortcut('0',
				'a');
		menu.add(Menu.NONE, Menu.FIRST + 2, Menu.NONE, "Help").setShortcut('1',
				'b');
		menu.add(Menu.NONE, Menu.FIRST + 3, Menu.NONE, "Quit").setShortcut('2',
				'c');

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		String title = item.getTitle().toString();
		switch (item.getItemId()) {

		case Menu.FIRST + 1:
			finish();
			break;
		case Menu.FIRST + 2:
			Toast.makeText(this, "Your Choice: " + title, Toast.LENGTH_LONG)
					.show();
			break;
		case Menu.FIRST + 3:
			show_alert();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void show_alert() {

		AlertDialog.Builder alert_box = new AlertDialog.Builder(this);
		alert_box.setMessage("Do you want to quit the app?");
		alert_box.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						onDestroy();
					}
				});

		alert_box.setNegativeButton("No",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});

		alert_box.show();
	}

	/*
	public void onDestroy() {
		super.onDestroy();
		android.os.Process.killProcess(android.os.Process.myPid());
	}
	*/

	public void onItemSelected(AdapterView arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		/*
		HashMap<String, String> item = new HashMap<String, String>();
		item = mylist.get(position);
		String typeID = item.get("ItemText").toString();
		Intent intent = new Intent();
		intent.setClass(this, TypeTreeActivity.class);
		intent.putExtra("typeID", typeID);
		startActivityForResult(intent, REQUEST_CODE);
		*/
		
		HashMap<String, String> item = new HashMap<String, String>();
		item = mylist.get(position);
		String typeID = item.get("ItemText").toString();
		Intent intent = new Intent();
		intent.setClass(this, TypeTreeActivity.class);
		intent.putExtra("typeID", typeID);
		startActivity(intent);
	}

	public void onNothingSelected(AdapterView arg0) {
		// TODO Auto-generated method stub

	}

}
